<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-card class="search-wrapper">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="账套名称" prop="accountSetName">
          <el-input
            v-model="queryParams.accountSetName"
            placeholder="请输入账套名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区 -->
    <el-card class="table-wrapper">
      <template #header>
        <div class="card-header">
          <el-button type="primary" @click="handleAdd">新增账套</el-button>
          <el-switch
            v-model="isCardView"
            active-text="卡片视图"
            inactive-text="表格视图"
            @change="handleViewChange"
          />
        </div>
      </template>

      <!-- 表格视图 -->
      <el-table
        v-if="!isCardView"
        v-loading="loading"
        :data="accountList"
        border
      >
        <el-table-column label="单位名称" prop="companyName" />
        <el-table-column label="账套ID" prop="accountSetId" width="80" />
        <el-table-column label="当前记账年月" width="120">
          <template #default="scope">
            {{ getCurrentYearMonth() }}
          </template>
        </el-table-column>
        <el-table-column label="账套启用年月" width="120">
          <template #default="scope">
            {{ formatYearMonth(scope.row.startYear, scope.row.startMonth) }}
          </template>
        </el-table-column>
        <el-table-column label="会计准则" prop="accountingStandards" width="120">
          <template #default="scope">
            {{ scope.row.accountingStandards === '1' ? '小企业会计准则' : '企业会计准则' }}
          </template>
        </el-table-column>
        <el-table-column label="资金模块" width="80">
          <template #default="scope">
            <el-tag :type="Number(scope.row.fundModuleStatus) === 1 ? 'success' : 'info'">
              {{ Number(scope.row.fundModuleStatus) === 1 ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="资产模块" width="80">
          <template #default="scope">
            <el-tag :type="Number(scope.row.assetModuleStatus) === 1 ? 'success' : 'info'">
              {{ Number(scope.row.assetModuleStatus) === 1 ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="凭证审核" width="80">
          <template #default="scope">
            <el-tag :type="Number(scope.row.voucherAuditStatus) === 1 ? 'success' : 'info'">
              {{ Number(scope.row.voucherAuditStatus) === 1 ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="账套权限" width="120">
          <template #default="scope">
            <el-tooltip 
              :content="scope.row.accountSetManager ? `管理员：${scope.row.accountSetManager}` : '暂无管理员'" 
              placement="top"
            >
              <span class="admin-accountSetManager">
                {{ scope.row.accountSetManager || '暂无管理员' }}
              </span>
            </el-tooltip>
            
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button type="text" @click="handleEdit(scope.row)">修改</el-button>
            <el-button type="text" @click="handleDelete(scope.row)" style="color: #F56C6C">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 卡片视图 -->
      <div v-else class="card-view">
        <el-row :gutter="16">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="item in accountList" :key="item.id">
            <el-card class="account-card" shadow="hover">
              <template #header>
                <div class="card-title">
                  <span>{{ item.companyName }}</span>
                  <span class="account-id">账套ID: {{ item.accountSetId }}</span>
                </div>
              </template>
              <div class="card-content">
                <p><label>当前记账年月：</label>{{ getCurrentYearMonth() }}</p>
                <p><label>账套启用年月：</label>{{ formatYearMonth(item.startYear, item.startMonth) }}</p>
                <p><label>会计准则：</label>{{ item.accountingStandards === '1' ? '小企业会计准则' : '企业会计准则' }}</p>
                <div class="module-tags">
                  <el-tag :type="Number(item.fundModuleStatus) === 1 ? 'success' : 'info'" size="small">
                    资金模块{{ Number(item.fundModuleStatus) === 1 ? '已启用' : '未启用' }}
                  </el-tag>
                  <el-tag :type="Number(item.assetModuleStatus) === 1 ? 'success' : 'info'" size="small">
                    资产模块{{ Number(item.assetModuleStatus) === 1 ? '已启用' : '未启用' }}
                  </el-tag>
                  <el-tag :type="Number(item.voucherAuditStatus) === 1 ? 'success' : 'info'" size="small">
                    凭证审核{{ Number(item.voucherAuditStatus) === 1 ? '已启用' : '未启用' }}
                  </el-tag>
                </div>
                <p>
                  <label>账套管理员：</label>
                  <span>{{ item.accountSetManager || '暂无管理员' }}</span>
                </p>
                <div class="card-actions">
                  <el-button type="text" @click="handleEdit(item)">修改</el-button>
                  <el-button type="text" @click="handleDelete(item)" style="color: #F56C6C">删除</el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 分页 -->
      <pagination
        v-if="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="accountForm" :model="form" :rules="rules" label-width="120px">
        <!-- 基本信息 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="账套名称" prop="accountSetName">
              <el-input v-model="form.accountSetName" placeholder="请输入账套名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="启用年月" prop="startYear">
              <el-select v-model="form.startYear" placeholder="请选择启用年" clearable>
                <el-option
                  v-for="year in yearOptions"
                  :key="year"
                  :label="year + '年'"
                  :value="year"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="startMonth">
              <el-select v-model="form.startMonth" placeholder="请选择启用月" clearable>
                <el-option
                  v-for="month in monthOptions"
                  :key="month"
                  :label="month + '月'"
                  :value="month"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="会计准则" prop="accountingStandards">
              <el-radio-group v-model="form.accountingStandards">
                <el-radio label="1" value="1">小企业会计准则</el-radio>
                <el-radio label="2" value="2">企业会计准则</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="行业" prop="industry">
              <el-select v-model="form.industry" placeholder="请选择">
                <el-option label="行业1" value="1" />
                <el-option label="行业2" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="增值税种类" prop="vatType">
              <el-radio-group v-model="form.vatType">
                <el-radio label="1" value="1">小规模纳税人</el-radio>
                <el-radio label="2" value="2">一般纳税人</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 模块/菜单设置 -->
        <el-divider content-position="left" v-if="bj==1">模块/菜单设置</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="资产模块" prop="assetModuleStatus" v-if="bj==1">
              <el-radio-group v-model="form.assetModuleStatus">
                <el-radio :label="1" value="1">启用({{ form.assetModuleStartDate }})</el-radio>
                <el-radio :label="0" value="0">不启用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="资金模块" prop="fundModuleStatus" v-if="bj==1">
              <el-radio-group v-model="form.fundModuleStatus">
                <el-radio :label="1" value="1">启用</el-radio>
                <el-radio :label="0" value="0">不启用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="前往进销存" prop="inventoryModuleStatus" v-if="bj==1">
              <el-radio-group v-model="form.inventoryModuleStatus">
                <el-radio :label="1" value="1">显示</el-radio>
                <el-radio :label="0" value="0">不显示</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 系统参数 -->
        <el-divider content-position="left" v-if="bj==1">系统参数</el-divider>

        <el-row :gutter="20">
          <el-col :span="24">
              <el-form-item label="凭证审核" prop="voucherAuditStatus" v-if="bj==1" >
              <el-radio-group v-model="form.voucherAuditStatus">
                <el-radio :label="1" value="1">审核</el-radio>
                <el-radio :label="0" value="0">不审核</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="资产负债表辅助核算余额额取值方式" prop="balanceSheetAuxiliaryCalculation" v-if="bj==1" >
              <el-radio-group v-model="form.balanceSheetAuxiliaryCalculation">
                <el-radio :label="1" value="1">所有辅助核算余额参与计算</el-radio>
                <el-radio :label="2" value="0">仅供应商/客户辅助核算余额参与计算</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="单价/数量/汇率小数" prop="decimalPlaces" v-if="bj==1">
              <el-select v-model="form.decimalPlaces" placeholder="请选择">
                <el-option label="8" value="8" />
                <el-option label="4" value="4" />
                <el-option label="2" value="2" />
                <el-option label="0" value="0" />
                <!-- 可以添加更多选项 -->
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 纳税人信息 -->
        <el-divider content-position="left" v-if="bj==1">纳税人信息</el-divider>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="公司名称" prop="companyName" v-if="bj==1">
              <el-input v-model="form.companyName" placeholder="请输入公司名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="统一社会信用代码" prop="unifiedSocialCreditCode" v-if="bj==1">
              <el-input v-model="form.unifiedSocialCreditCode" placeholder="请输入统一社会信用代码" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="报税地区" prop="taxReportArea" v-if="bj==1"  >
              <el-select v-model="form.taxReportArea" placeholder="请选择">
                <el-option label="地区1" value="1" />
                <el-option label="地区2" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Account">
import { listAccount, getAccount, delAccount, addAccount, updateAccount } from "@/api/account/account";

const { proxy } = getCurrentInstance();

const accountList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const isCardView = ref(false);
const bj = ref(0);

// 获取当前年月
const currentDate = new Date();
const currentYear = currentDate.getFullYear();
const currentMonth = currentDate.getMonth() + 1; // getMonth() 返回 0-11，需要加1

// 年份选项（前5年到后5年）
const yearOptions = computed(() => {
  const currentYear = new Date().getFullYear();
  const years = [];
  for (let i = currentYear - 5; i <= currentYear + 5; i++) {
    years.push(i);
  }
  return years;
});

// 月份选项（1-12月）
const monthOptions = computed(() => {
  return Array.from({ length: 12 }, (_, i) => i + 1);
});

const data = reactive({
  form: {
    id: null,
    accountSetId: null,
    accountSetName: null,
    companyName: null,
    startYear: null,
    startMonth: null,
    vatType:null,
    accountingStandards: null,
    companyName:null,
    unifiedSocialCreditCode:null,
    taxReportArea:null,
    unitName:null,
    accountSetManager:null,
    otherRolePermissions:null,
    assetModuleStatus:1,
    assetModuleStartDate:null,
    fundModuleStatus:1,
    inventoryModuleStatus:1,
    voucherAuditStatus:0,
    balanceSheetAuxiliaryCalculation:1,
    decimalPlaces:null,
    loginMethod:null,
    taxDeclarationPersonName:null,
    taxDeclarationPersonPhone:null,
    taxDeclarationPassword:null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    accountSetName: null,
    startYear: null,
    startMonth: null,
    accountingStandards: null,
    industry: null,
    vatType: null,
    companyName: null,
    unifiedSocialCreditCode: null,
    taxReportArea: null
  },
  rules: {
    accountSetName: [
      { required: true, message: "账套名称不能为空", trigger: "blur" }
    ],
    startYear: [
      { required: true, message: "启用年不能为空", trigger: "change" }
    ],
    startMonth: [
      { required: true, message: "启用月不能为空", trigger: "change" }
    ],
    accountingStandards: [
      { required: true, message: "会计准则不能为空", trigger: "change" }
    ],
    vatType: [
      { required: true, message: "增值税种类不能为空", trigger: "change" }
    ],
    companyName: [
      { required: true, message: "单位名称不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询存储账套基础信息及所属公司税务相关信息列表 */
function getList() {
  loading.value = true;
  listAccount(queryParams.value).then(response => {
    accountList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    accountSetId: null,
    accountSetName: null,
    companyName: null,
    startYear: null,
    startMonth: null,
    accountingStandards: null,
    vatType: null,
    inventoryModuleStatus: 1,
    fundModuleStatus: 1,  // 默认启用
    assetModuleStatus: 1, // 默认启用
    voucherAuditStatus: 0, // 默认不启用
  };
  proxy.resetForm("accountForm");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryForm");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// 生成账套ID
function generateAccountId() {
  const now = new Date();
  const year = now.getFullYear();
  const month = (now.getMonth() + 1).toString().padStart(2, '0');
  const day = now.getDate().toString().padStart(2, '0');
  const hours = now.getHours().toString().padStart(2, '0');
  const minutes = now.getMinutes().toString().padStart(2, '0');
  const seconds = now.getSeconds().toString().padStart(2, '0');
  
  // 将字符串转换为数值
  return Number(`${year}${month}${day}${hours}${minutes}${seconds}`);
}

/** 新增按钮操作 */
function handleAdd() {
  reset(); // 使用基础字段重置
  form.value.accountSetId = generateAccountId();
  form.value.id = null;
  bj.value = 0;
  open.value = true;
  title.value = "添加存储账套基础信息及所属公司税务相关信息";
}

/** 修改按钮操作 */
function handleEdit(row) {
  // 修改时不调用 reset，直接用后端返回的完整数据覆盖
  getAccount(row.id).then(response => {
    bj.value = 1;
    form.value = response.data;
    open.value = true;
    title.value = "修改账套信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["accountForm"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateAccount(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        // 移除这里的ID生成，因为已经在handleAdd中生成了
        addAccount(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除账套"' + row.accountSetId + '"的数据？').then(function() {
    return delAccount(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 状态按钮操作 */
function handleStatusChange(row) {
  // 实现状态切换逻辑
  proxy.$modal.msgWarning("状态切换功能尚未实现");
}

function handleViewChange(value) {
  isCardView.value = value;
}

// 添加时间格式化函数
function formatCreateTime(time) {
  if (!time) return '';
  const date = new Date(time);
  const year = date.getFullYear();
  // 月份需要+1因为 getMonth() 返回 0-11
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  return `${year}年${month}月`;
}

// 格式化年月显示
function formatYearMonth(year, month) {
  if (!year || !month) return '-';
  return `${year}年${month.toString().padStart(2, '0')}月`;
}

// 处理权限设置
function handlePermission(row) {
  // 实现权限设置逻辑
  proxy.$modal.msgInfo("权限设置功能开发中");
}

// 获取当前年月的显示
function getCurrentYearMonth() {
  const now = new Date();
  const year = now.getFullYear();
  const month = (now.getMonth() + 1).toString().padStart(2, '0');
  return `${year}年${month}月`;
}

getList();
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .search-wrapper {
    margin-bottom: 20px;
  }

  .table-wrapper {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }

  :deep(.el-dialog__body) {
    padding: 20px 40px;
    
    .el-form-item {
      margin-bottom: 20px;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
    
    .el-select {
      width: 100%;
    }
    
    .el-radio-group {
      display: flex;
      flex-direction: column;
      gap: 12px;

      .radio-line {
        display: flex;
        align-items: center;
      }
    }

    // 禁用状态下的输入框样式
    .el-input.is-disabled .el-input__inner {
      color: #606266;
      background-color: #f5f7fa;
    }
  }

  .card-view {
    .account-card {
      margin-bottom: 16px;
      font-size: 13px;
      
      .card-title {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        span {
          font-weight: bold;
          font-size: 14px;
        }

        .account-id {
          font-size: 12px;
          color: #909399;
        }
      }
      
      .card-content {
        p {
          margin: 6px 0;
          display: flex;
          align-items: center;
          
          label {
            color: #909399;
            margin-right: 8px;
            min-width: 90px;
          }
        }
        
        .module-tags {
          margin: 8px 0;
          display: flex;
          flex-wrap: wrap;
          gap: 6px;
          
          .el-tag {
            margin: 0;
            font-size: 12px;
            padding: 0 6px;
            height: 22px;
            line-height: 20px;
          }
        }
        
        .card-actions {
          display: flex;
          justify-content: flex-end;
          margin-top: 12px;
          border-top: 1px solid #EBEEF5;
          padding-top: 10px;
          
          .el-button {
            padding: 0 6px;
            font-size: 13px;
            
            & + .el-button {
              margin-left: 10px;
            }
          }
        }
      }
    }
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .admin-name {
    display: inline-block;
    max-width: 120px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    vertical-align: middle;
    margin-right: 8px;
  }

  .permission-btn {
    padding: 0 8px;
  }
}
</style>
